package com.tongcao.cn.contoller.websocket;

import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author:tongcao
 * @since:2019/8/16 10:45
 * Description:日志输出
 */

@RestController
@ServerEndpoint("/log")
public class LogWebSocketHandle {


    private Process process;

    private InputStream inputStream;


    /**
     * 新的WebSocket请求开启
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {


        try {
            process = Runtime.getRuntime().exec("tail -f /usr/log/booker.log");
            inputStream = process.getInputStream();

            // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
            final TailLogThread thread = new TailLogThread(inputStream, session);

            thread.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * WebSocket请求关闭
     */
    @OnClose
    public void onClose() {
        try {
            if (inputStream != null)
                inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (process != null)
            process.destroy();
    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }
}